﻿using _9jCardRegisterCollection.Models;
using AntdUI;
using CardRegisterCollection.BLL;
using CardRegisterCollection.Model;
using CardRegisterCollection.Utility.Enum;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Menu = CardRegisterCollection.Model.Menu;

namespace _9jCardRegisterCollection.Views
{
    public partial class CardTypeManagementPage : UserControl
    {
        private AntdUI.Window window;
        public CardTypeManagementPage(AntdUI.Window _window)
        {
            window = _window;
            InitializeComponent();

            //初始化表格列头
            InitTableColumns();
            this.cmbCardType.SelectedIndex = 0;
            InitData();
            BindEventHandler();
        }

        CardRegisterCollection.BLL.CardType cardTypeHelper = new CardRegisterCollection.BLL.CardType();

        AntList<CardTypeForTable> cardTypes;

        private void InitTableColumns()
        {
            tabCardType.Columns = new ColumnCollection() {
                new ColumnCheck("Selected"){Fixed = true},
                new Column("Id", "证件ID", ColumnAlign.Center)
                {
                    Visible = false,
                },
                new Column("Name", "证件名称", ColumnAlign.Center)
                {
                    Width="250",
                    //设置树节点，名称需和User里的User[]名称保持一致
                    KeyTree = "ChildTypes",
                    Align = ColumnAlign.Left,
                    ColAlign = ColumnAlign.Center
                },
                new Column("ParentId", "父编号", ColumnAlign.Center)
                {
                    Visible=false,
                },
                new Column("sort", "排序", ColumnAlign.Center)
                {
                    Visible = false,
                },
                new Column("Type", "证件类型",ColumnAlign.Center),
                new Column("CellLinks", "操作", ColumnAlign.Center)
                {
                    Fixed = true,//冻结列
                }
            };
        }


        private void InitData()
        {
            cardTypes = new AntList<CardTypeForTable>();
            //tabCardType.Binding(cardTypes);
            DataSet ds = new DataSet(); 
            string strWhere = string.Empty;
            switch (cmbCardType.SelectedIndex)
            {
                case 0:
                    strWhere = "  type = '" + CardTypeEnum.境内人员证件 .ToString() + "' ";
                    break;
                case 1:
                    strWhere = "  type = '" + CardTypeEnum.境外人员证件.ToString() + "' ";
                    break;
                case 2:
                    strWhere = "  type = '" + CardTypeEnum.车辆证件.ToString() + "' ";
                    break;
                default:
                    break;
            }
            if (txtKeyword.Text.Trim().Length > 0)
            {
                strWhere += "and name like '%" + txtKeyword.Text.Trim().ToString() + "%' ";
            }
            ds = cardTypeHelper.GetList(strWhere);
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                for (int i = 0; i < dt.Rows.Count; i++)
                {   //获取证件大类
                    if (dt.Rows[i]["ParentId"].ToString().Equals("0"))
                    {
                        cardTypes.Add(new CardTypeForTable
                        {
                            Id = dt.Rows[i]["Id"].ToString() ,
                            Name = dt.Rows[i]["name"].ToString(),
                            Type = dt.Rows[i]["type"].ToString(),
                            ParentId = dt.Rows[i]["ParentId"].ToString(),
                            CreatedBy= dt.Rows[i]["CreatedBy"].ToString(),
                            CreatedAt =Convert.ToDateTime( dt.Rows[i]["CreatedAt"].ToString()), 
                            CellLinks = new CellLink[] {
                            new CellButton(Guid.NewGuid().ToString(),"添加",TTypeMini.Success),
                            new CellButton(Guid.NewGuid().ToString(),"编辑",TTypeMini.Primary),
                            new CellButton(Guid.NewGuid().ToString(),"删除",TTypeMini.Error) },
                        });
                        //获取证件子类
                        List<CardTypeForTable> list = new List<CardTypeForTable>();
                        for (int j = 0; j < dt.Rows.Count; j++)
                        {
                            if (dt.Rows[j]["ParentId"].ToString().Equals(dt.Rows[i]["Id"].ToString()))
                            {
                                list.Add(new CardTypeForTable
                                {
                                    Id = dt.Rows[j]["Id"].ToString(),
                                    Name = dt.Rows[j]["name"].ToString(),
                                    Type = dt.Rows[j]["type"].ToString(), 
                                    ParentId =  dt.Rows[i]["Id"].ToString() ,
                                    CreatedBy = dt.Rows[i]["CreatedBy"].ToString(),
                                    CreatedAt = Convert.ToDateTime(dt.Rows[i]["CreatedAt"].ToString()), 
                                    CellLinks = new CellLink[] { 
                                     new CellButton(Guid.NewGuid().ToString(),"编辑",TTypeMini.Primary),
                                     new CellButton(Guid.NewGuid().ToString(),"删除",TTypeMini.Error) },
                                });
                            }
                        }
                        cardTypes[cardTypes.Count - 1].ChildTypes = list.ToArray();
                    }
                } 
                
            }
            tabCardType.Binding(cardTypes);
        }

        private void butSearch_Click(object sender, EventArgs e)
        {
            InitData();
        }

        private void BindEventHandler()
        {
            tabCardType.CellButtonClick += tabCardType_CellButtonClick;
        }

        private void tabCardType_CellButtonClick(object sender, TableButtonEventArgs e)
        {
            var buttontext = e.Btn.Text;
            if (e.Record is CardTypeForTable card)
            {
                switch (buttontext)
                {
                    //暂不支持进入整行编辑，只支持指定单元格编辑，推荐使用弹窗或抽屉编辑整行数据
                    case "编辑":
                        { 
                            var form = new CardTypeEdit(window, GetCardTypeWithUpdate(card)) { Size = new Size(500, 300) };
                            AntdUI.Drawer.open(new AntdUI.Drawer.Config(window, form)
                            {
                                OnLoad = () =>
                                {
                                    AntdUI.Message.info(window, "进入编辑", autoClose: 1); 
                                },
                                OnClose = () =>
                                {
                                    AntdUI.Message.info(window, "结束编辑", autoClose: 1); 
                                    InitData();
                                }
                            });
                            InitData();
                        }
                        break;
                    case "删除":
                        var result = Modal.open(window, "删除警告！", "确认要删除选择的数据吗？", TType.Warn);
                        if (card.ChildTypes!=null&&card.ChildTypes.Length>0)
                        {
                            Modal.open(window, "删除警告！", "请先删除该证件类型下其他证件数据！", TType.Warn);
                            return;
                        }
                        if (result == DialogResult.OK)
                        {
                            cardTypeHelper.Delete(card.Id);
                            InitData();
                        } 
                        break;
                    case "添加":
                        {
                            var form = new CardTypeEdit(window, GetCardTypeWithAdd(card)) { Size = new Size(500, 300) };
                            AntdUI.Drawer.open(new AntdUI.Drawer.Config(window, form)
                            {
                                OnLoad = () =>
                                {
                                    AntdUI.Message.info(window, "开始添加", autoClose: 1);
                                },
                                OnClose = () =>
                                {
                                    AntdUI.Message.info(window, "结束添加", autoClose: 1); 
                                    InitData();
                                }
                            });
                            InitData();
                        }

                        break;
                        default: break;
                }
            }
        }
        private CardRegisterCollection.Model.CardType GetCardTypeWithUpdate(CardTypeForTable cardTypeForTable)
        {
            CardRegisterCollection.Model.CardType cardType = new CardRegisterCollection.Model.CardType()
            {
                Id = cardTypeForTable.Id.ToString(), 
                name = cardTypeForTable.Name,
                ParentId = cardTypeForTable.ParentId,
                 sort = cardTypeForTable.Sort,
                Type = this.cmbCardType.Text 
            };
            //var Id = tabCardType;
            //tabCardType.Rowse;
            return cardType;
        }
        private CardRegisterCollection.Model.CardType GetCardTypeWithAdd(CardTypeForTable cardTypeForTable)
        {
            CardRegisterCollection.Model.CardType cardType = new CardRegisterCollection.Model.CardType()
            {
                Id=Guid.NewGuid().ToString(), 
                ParentId = cardTypeForTable.Id ,
                sort = cardTypeForTable.Sort,
                Type = this.cmbCardType.Text,
                CreatedBy = CurrentLoginInfo.UserInfo.UserName,
                CreatedAt = DateTime.Now, 
            };
            //var Id = tabCardType;
            //tabCardType.Rowse;
            return cardType;
        }
        private void cmbCardType_SelectedIndexChanged(object sender, IntEventArgs e)
        {
            InitData();
        }

        private void buttonADD_Click(object sender, EventArgs e)
        {
            var form = new CardTypeEdit(window, AddMainCardType()) { Size = new Size(500, 300) };
            AntdUI.Drawer.open(new AntdUI.Drawer.Config(window, form)
            {
                OnLoad = () =>
                {
                    AntdUI.Message.info(window, "开始添加", autoClose: 1);
                },
                OnClose = () =>
                {
                    AntdUI.Message.info(window, "结束添加", autoClose: 1);

                    InitData();
                }
            });
    
        }
        private CardRegisterCollection.Model.CardType AddMainCardType()
        {
            CardRegisterCollection.Model.CardType cardType = new CardRegisterCollection.Model.CardType()
            {
                Id  = Guid.NewGuid().ToString(), 
                ParentId = "0",
                sort = 1,
                Type = this.cmbCardType.Text,
                CreatedBy = CurrentLoginInfo.UserInfo.UserName,
                CreatedAt = DateTime.Now, 
            };
            //var Id = tabCardType;
            //tabCardType.Rowse;
            return cardType;
        }
    }

}
